var HostUrl = function(str) {
	HOST = str;
}

var animationIn = 'pop-in';
var animationOut = 'pop-out';

//var baseUrl = 'http://127.0.0.1:4166/Mobile/';
//var baseUrl = 'https://5car.top/api/Mobile/';
var baseUrl = "http://test.weixin.zzxc.org.cn/";
var api = {
	GetUserStatus: 'api/WxLogin/GetUserStatus',
	Login: "api/WxLogin/Login",
	SmsSend: "api/Sms/SmsSend"
};

/*
 * message常量
 */
var msg = {
	GLITZHOME: 'zzxc',
	NETWORK_IS_UNAVAILABLE: "网络连接失败，请检查您的网络.",
	LOAD_DATA_FAIL: '加载数据失败，请等一会再试!',
	AUTH_EXPIRED: '认证信息失效，请重新登录！',
	SERVER_ERROR: '服务响应失败！',
};

/*
 * APP版本号
 */
var curAppVer = "1.0.1";
/*
 * 工具类
 */
var tool = {
	isEmptyVal: function(val) {
		if(val === null || typeof(val) === 'undefined' || val === '')
			return true;

		return false;
	},
	isFunction: function(f) {
		return Object.prototype.toString.call(f) === "[object Function]";
	},
	isObject: function(o) {
		return Object.prototype.toString.call(o) === "[object Object]";
	},
	isString: function(s) {
		return Object.prototype.toString.call(s) === "[object String]";
	}
};

/* 
 * 保存数据
 * 注：目前使用h5的localStorage, 只能非跨域下工作
 */
function cache(key, val) {
	if(key === 'clear') {
		window.localStorage.clear();
	} else if(val === null) {
		window.localStorage.removeItem(key);
	} else if(val) {
		window.localStorage[key] = val;
	} else {
		return window.localStorage[key];
	}
}

var animation = {
	popIn: 'pop-in',
	popOut: 'pop-out',
	slideInRight: 'slide-in-right',
	slideOutRight: 'slide-out-right',
	slideInBottom: 'slide-in-bottom',
	slideOutBottom: 'slide-out-bottom',
}

var app = {
	map: function(elements, callback) {
		var value, values = [],
			i, key, len;
		if(typeof elements.length === 'number') { //TODO 此处逻辑不严谨，可能会有Object:{a:'b',length:1}的情况未处理
			for(i = 0, len = elements.length; i < len; i++) {
				value = callback(elements[i], i);
				if(value != null) values.push(value);
			}
		} else {
			for(key in elements) {
				value = callback(elements[key], key);
				if(value != null) values.push(value);
			}
		}
		return values.length > 0 ? [].concat.apply([], values) : values;
	},
	gotoNextRegisterPage: function(userinfo, type) {
		//if(tool.isEmptyVal(userinfo.UID)) {
		if(userinfo == null) {
			//TODO 如果uid为空的话，还没有注册，先注册手机号
			openPage('register_phone.html', 'register_phone');
		} else if(type == 1 && tool.isEmptyVal(userinfo.idcard)) {
			//TODO 如果type=1说明需要注册详细信息，如果身份证号为空，需要进入详细注册页面
			openPage('register_detail.html', 'register_detail');
		}
	}
};

function GetQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) return unescape(r[2]);
	return null;
}

function numTozh(num) {
	switch(num) {
		case 0:
			return '零';
			break;

		case 1:
			return '一';
			break;
		case 2:
			return '二';
			break;
		case 3:
			return '三';
			break;
		case 4:
			return '四';
			break;
		case 5:
			return '五';
			break;
		case 6:
			return '六';
			break;
		case 7:
			return '七';
			break;
		case 8:
			return '八';
			break;
		case 9:
			return '九';
			break;
		default:
			return '';
			break;
	}
}

function getStarTxt(val) {
	if(val == 1)
		return "很差";
	else if(val == 2)
		return "较差";
	else if(val == 3)
		return "一般";
	else if(val == 4)
		return "良好"
	else if(val == 5)
		return "优秀";
}

/*
 * 封装常用的打开窗口，一般只需传入url及id
 * 默认显示等待框，默认不自动显示
 */
function openPage(url, id, extraObj, styleObj, showObj, waitObj, extrasObj) {
	showObj = showObj || {
		autoShow: true
	};
	waitObj = waitObj || {
		autoShwo: true
	}; // 默认显示等待框

	extrasObj = extrasObj || {};

	mui.openWindow({
		url: url,
		id: id,
		styles: styleObj,
		extras: extraObj,
		show: showObj,
		waiting: waitObj
	});
}

function showPage(wv, aniShow, closeWaiting, duration) {
	if(tool.isEmptyVal(wv)) {
		console.log('webview为空');
		return;
	}
	aniShow = aniShow || animation.popIn;
	duration = duration || (mui.os.ios ? 300 : 250); // pop-in动画在ios平台上300ms为佳，在android平台上250为佳
	wv.show(aniShow, duration);

}

/*
 *
 * 判断数组是否包含某元素
 */
function arrayContains(a, obj) {
	var i = a.length;
	while(i--) {
		if(a[i] === obj) {
			return true;
		}
	}
	return false;
}

/*
 * 数据访问
 */
var persistent = {
	userStatus: function() {
		var userstatus = cache('userStatus');

		return userstatus;
	},
}

var ajaxStatus = {
	OK: 200,
	ERROR: 300,
	FAIL_AUTH: 400,
};

/*
 * 封装ajax
 */
var ajax = {
	getAuthHeader: function() {
		return persistent.uid() + ',' + persistent.utoken() + ',' + persistent.postcode() + ',' + 'sign';
	},
	post: function(url, paramObj, suc, wait, comp, err) {
		var sign = "";
		for(var param in paramObj) {
			sign += param + "=" + paramObj[param] + "&";
		}
		var tick = parseInt(new Date().getTime() / 1000);
		sign += "r=" + tick;
		sign = md5(sign);
		// 检测网络是否可用

		if(tool.isObject(url)) {
			paramObj = url.paramObj;
			suc = url.suc;
			wait = url.wait;
			comp = url.comp;
			err = url.err;
			url = url.url;
		}

		paramObj = paramObj || {};
		// uri编码
		for(var k in paramObj) {
			var v = paramObj[k];
			if(tool.isString(v)) {
				v = v.replace(/\\/g, '\\\\');
				paramObj[k] = encodeURIComponent(v);
			}
			// 只处理两层，应该够了
			else if(tool.isObject(v)) {
				for(var kk in v) {
					var vv = v[kk];
					if(tool.isString(vv)) {
						vv = vv.replace(/\\/g, '\\\\');
						v[kk] = encodeURIComponent(vv);
					}
				}
			}

		}

		var headerObj = {
			"sign": sign,
			"tick": tick,
			"cpid": "100001"
		};
		/*		if(url !== api.Coach.login &&
					url !== api.system.checkforupdate) {
					paramObj.Authorization = this.getAuthHeader();
					//			headerObj.Authorization = this.getAuthHeader();
				}*/

		// 发送请求
		mui.ajax(url, {
			type: 'POST',
			timeout: 10000,
			data: paramObj,
			dataType: 'json',
			//contentType: "application/x-www-form-urlencoded", 
			headers: headerObj,
			success: function(data, textStatus, xhr) {
				if(textStatus == 'success') {
					if(data.status != null && data.status && data.message != null && data.message.trim() != "") {
						//plus.nativeUI.toast(data.message);
					}
					if(tool.isFunction(suc)) {

						suc(data, textStatus, xhr);
					}
				} else {
					var errMsg = data.msg || msg.LOAD_DATA_FAIL;
					//plus.nativeUI.toast(errMsg);
					//if (tool.isFunction(err)) err();
				}
				//				if (data.StatusCode === ajaxStatus.OK) {
				//					if (tool.isFunction(suc)) suc(data, textStatus, xhr);
				//				} else if (data.StatusCode === ajaxStatus.ERROR) {
				//					var errMsg = data.Msg || msg.LOAD_DATA_FAIL;
				//					plus.nativeUI.toast(errMsg);
				//					if (tool.isFunction(err)) err();
				//				} else if (data.StatusCode === ajaxStatus.FAIL_AUTH) {
				//					plus.nativeUI.toast(msg.AUTH_EXPIRED);
				//					mui.openWindow(plus.io.convertAbsoluteFileSystem('_www/login.html'), 'login', null);
				//					if (tool.isFunction(err)) err();
				//				} else {
				//					plus.nativeUI.toast(msg.SERVER_ERROR);
				//					if (tool.isFunction(err)) err();
				//				}
			},
			error: function(xhr, type) {
				console.log(xhr);
				//plus.nativeUI.toast(msg.LOAD_DATA_FAIL + "(" + type + ")");
				if(tool.isFunction(err)) err();
			},
			complete: function() {
				if(tool.isFunction(comp)) comp();
			}
		});
	},
};

/*
 * 用户相关的方法及属性
 */
var System = {
	smsSend: function(phoneNum, suc, err) {
		var params = {};
		params.recNum = phoneNum;
		ajax.post(baseUrl + api.SmsSend, params,
			function(data, textStatus, xhr) {
				console.log(data);
				suc(data);
			}, true, null,
			function(xhr, type) {
				err(xhr);
			});
	},
	autoLogin: function(unionID, recNum, suc, err) {
		var params = {};
		params.UnionId = unionID;

		ajax.post(baseUrl + api.AutoLogin, params,
			function(data, textStatus, xhr) {
				suc(data);
			}, true, null,
			function(xhr, type) {
				err(xhr);
			});
	},
	login: function(recNum, smsCode, suc, err) {
		var params = {};
		params.recNum = recNum;
		params.SmsCode = smsCode;
		ajax.post(baseUrl + api.Login, params,
			function(data, textStatus, xhr) {
				suc(data);
			}, true, null,
			function(xhr, type) {
				err(xhr);
			});
	},
	getUserStatus: function(suc, err) {
		var params = {};
		ajax.post(baseUrl + api.GetUserStatus, params,
			function(data, textStatus, xhr) {
				suc(data);
			}, true, null,
			function(xhr, type) {
				err(xhr);
			});
	}
};

//添加用户详细信息页相关方法及属性